package com.minstone.springmvcrestful.manager.security.interfaces.jdbc;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.minstone.springmvcrestful.manager.security.oauth.OauthClientDetails;
import com.minstone.springmvcrestful.manager.security.oauth.OauthRepository;

import static com.minstone.springmvcrestful.manager.security.interfaces.CacheConstants.CLIENT_DETAILS_CACHE;

/**
 * 2015/11/16
 *
 * @author Shengzhao Li
 */
@Repository("oauthRepositoryJdbc")
public class OauthRepositoryJdbc implements OauthRepository {


    private static OauthClientDetailsRowMapper oauthClientDetailsRowMapper = new OauthClientDetailsRowMapper();


    @Resource(name="jdbcTemplate")
    public JdbcTemplate jdbcTemplate;


    public OauthClientDetails findOauthClientDetails(String clientId) {
        final String sql = " select * from oauth_client_details where  client_id = ? ";
        final List<OauthClientDetails> list = this.jdbcTemplate.query(sql, new Object[]{clientId}, oauthClientDetailsRowMapper);
        return list.isEmpty() ? null : list.get(0);
    }

    public List<OauthClientDetails> findAllOauthClientDetails() {
        final String sql = " select * from oauth_client_details order by create_time desc ";
        return this.jdbcTemplate.query(sql, oauthClientDetailsRowMapper);
    }

    @CacheEvict(value = CLIENT_DETAILS_CACHE, key = "#clientId")
    public void updateOauthClientDetailsArchive(String clientId, boolean archive) {
        final String sql = " update oauth_client_details set archived = ? where client_id = ? ";
        this.jdbcTemplate.update(sql, archive, clientId);
    }

    public void saveOauthClientDetails(final OauthClientDetails clientDetails) {
        final String sql = " insert into oauth_client_details(client_id,resource_ids,client_secret,scope,authorized_grant_types,web_server_redirect_uri," +
                " authorities,access_token_validity,refresh_token_validity,additional_information,trusted,autoapprove) values (?,?,?,?,?,?,?,?,?,?,?,?)";

        this.jdbcTemplate.update(sql, new Object[]{
           clientDetails.clientId(),
           clientDetails.resourceIds(),

           clientDetails.clientSecret(),
           clientDetails.scope(),

           clientDetails.authorizedGrantTypes(),
           clientDetails.webServerRedirectUri(),

           clientDetails.authorities(),
           clientDetails.accessTokenValidity(),

           clientDetails.refreshTokenValidity(),
           clientDetails.additionalInformation(),

           clientDetails.trusted(),
           clientDetails.autoApprove()

        });
    }
}
